<template>
  <div>
    <div class="form-group">
      <span>选择回访问卷</span>
      <el-select v-model="value" placeholder="请选择" :disabled="this.btnDisable" @change="getQuestionTable">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </div>
    <FilterTable
      ref="table"
      :fetchapi="fetchApi"
      :columns="columns"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :height="230"
      :onSyncTableData="getQuestionAll"
    ></FilterTable>

    <div>
      <h1>本工单跟踪记录</h1>
      <FormPanel :list="formList" :isSubmitBtn="false" :collapse="false" :labelWidth="120" @formChange="changeHandle" />
    </div>

    <!-- 问卷录入 -->
    <BaseDialog ref="tablesingleCopy" :visible.sync="question" title="问卷信息录入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <questionnaireModify :selColumn="this.selectColumns" @saveQuestions="saveQuestions" @closeQuestionModify="closeQuestionModify" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getQuestionnaireInfo } from '@/api/customerRepair/visitRules/questionnaireMake2';
import { questionPag, addQuestion } from '@/api/customerRepair/customerCare/maintenanceRemind/index';
import questionnaireModify from '@/pages/customerRepair/customerCare/maintenanceRemind/questionnaireModify';

export default {
  components: {
    questionnaireModify
  },
  mixins: [dictionary],
  props: ['data', 'remindSource'],
  data() {
    return {
      fetchApi: questionPag,
      columns: this.createdTable(),
      fetchParams: { xhrAbort: true },
      options: [],
      value: '',
      formList: this.createFormList(),
      questionList: [],
      selectColumns: {},
      question: false,
      indexId: '',
      btnDisable: false,
      questionId: null
    };
  },
  computed: {
    formList3() {
      return this.formList;
    },
    tableList() {
      return this.questionList;
    },
    questionnaireId() {
      return this.questionId;
    }
  },
  mounted() {
    let itemList = this.formList.find(x => x.fieldName === 'traceStatus').itemList;
    this.formList.find(x => x.fieldName === 'traceStatus').itemList = itemList.slice(0, 4);
    this.createBaseTable();
    this.queryQuestionnaireInfo();
    this.pagesControl();
    this.getQuestionTable();
  },
  methods: {
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          fixed: 'left',
          disabled: this.btnDisable,
          render: props => {
            return (
              <el-button type="text" size="mini" disabled={this.btnDisable} title="编辑" onClick={() => this.openQuestion(props.row)}>
                编辑
              </el-button>
            );
          }
        },
        {
          title: '问卷名称',
          dataIndex: 'questionnaireName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '问题名称',
          dataIndex: 'questionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '问题内容',
          dataIndex: 'questionContent',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '类型',
          dataIndex: 'questionType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.questionType, '8074')}</div>;
          }
        },
        {
          title: '必填',
          dataIndex: 'isMustFilled',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.isMustFilled, '1004')}</span>;
          }
        },
        {
          title: '答案',
          dataIndex: 'answer',
          sorter: true,
          filter: true
          // editable: true,
          // editType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true
          // editable: true,
          // editType: 'input'
        }
      ];
    },

    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '跟踪状态',
          fieldName: 'traceStatus',
          initialValue: '',
          itemList: this.createDictList('8058'),
          change: val => this.selectChange(val)
        },
        {
          type: 'SELECT',
          label: '回访失败原因',
          fieldName: 'reviewFailed',
          initialValue: '',
          itemList: this.createDictList('8084'),
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '是否三日电访(车辆)',
          fieldName: 'isTraceVehiele',
          initialValue: '1',
          itemList: this.createDictList('8069')
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          selfCols: 1.5,
          rows: 4
        },
        {
          type: 'TEXT_AREA',
          label: '下次维修提醒',
          fieldName: 'nextRepairRemind',
          selfCols: 1.5,
          rows: 4,
          maxlength: 100
        }
      ];
    },

    createBaseTable() {
      this.BaseTable = this.$refs.table.$refs.pageTable;
    },

    // 获取问卷类型
    async queryQuestionnaireInfo() {
      console.log(this.data, 'this.data');
      console.log(this.remindSource, 'remindsource');
      //  questionnaire
      let obj = {
        isTemplate: '10041002',
        isValid: '10041001',
        questionnaireType: '80031001'
      };
      let isSprayLabour = this.data.isSprayLabour;
      if (isSprayLabour === 10041001) {
        obj.questionnaireType = '80031002';
      }
      // if (this.remindSource === 1) {
      //   obj.questionnaireType = '80031003';
      // }
      console.log(obj, 'obj');
      const res = await getQuestionnaireInfo(obj); // 查询问卷（不查模板）
      this.options = res.data.rows.map(x => ({ value: x.QUESTIONNAIRE_ID, label: x.QUESTIONNAIRE_NAME, index: x.index, disabled: false }));
      // console.log(this.options)
      this.options = [...this.options];
    },

    // 页面管控
    pagesControl() {
      let isTrace = this.data.traceStatus;
      if (isTrace === 80581003 || isTrace === 80581004) {
        this.formList.forEach(x => {
          x.disabled = true;
        });
      }
      this.formList = [...this.formList];
    },

    // 获取问卷表格数据
    getQuestionTable(val) {
      let obj = {
        questionType: '80031001',
        questionId: val,
        itemId: this.data.item_id || null,
        roNo: this.data.roNo || null
      };
      let isSprayLabour = this.data.isSprayLabour;
      if (isSprayLabour === 10041001) {
        obj.questionType = '80031002';
      }
      // if (this.remindSource === 1) {
      //   obj.questionType = '80031003';
      // }
      this.questionId = val;
      console.log(obj, 'isSprayLabour');
      this.fetchParams = Object.assign({}, obj, { xhrAbort: false });
    },

    // 获得问题数据
    getQuestionAll(val) {
      let isTrace = this.data.traceStatus;
      // console.log(isTrace,'istrave');
      console.log(val, 'val');
      this.questionList = val;
      if (val && val.length > 0) {
        if (isTrace === 80581003 || isTrace === 80581004) {
          this.BaseTable.SET_DISABLE_SELECT(val);
          this.options.map(x => {
            x.disabled = true;
          });
          this.btnDisable = true;
        }
      }
    },

    openQuestion(val) {
      this.selectColumns = val;
      this.indexId = val.questionId;
      let isTrace = this.data.TRACE_STATUS;
      if (isTrace == 80581003 || isTrace === 80581004) {
        this.question = false;
      } else {
        this.question = true;
      }
    },

    // 修改数据
    saveQuestions(val) {
      this.question = false;
      this.questionList.forEach(x => {
        if (x.questionId == this.indexId) {
          // console.log(val,'val');
          // console.log(x,'x');
          x.questionContent = val.find(y => y.fieldName === 'QUESTION_CONTENT').initialValue;
          x.remark = val.find(y => y.fieldName === 'remark').initialValue;
          if (x.questionType == 80741001) {
            x.answer = val.find(y => y.fieldName === 'answer').initialValue;
          } else if (x.questionType == 80741002) {
            x.answer = val.find(y => y.fieldName === 'dynamicRadioSelect').initialValue;
          } else if (x.questionType == 80741003) {
            let list = val.find(y => y.fieldName === 'dynamicMultipleSelect').initialValue;
            let str = '';
            console.log(list, 'list');
            for (let i = 0; i < list.length; i++) {
              if (i === 0) {
                str = list[0];
              } else {
                str = str + ',' + list[i];
              }
            }
            // console.log(str, 'str');
            x.answer = str;
          }
        }
      });
      console.log(this.questionList, 'this.questionList');
    },

    closeQuestionModify(val) {
      this.question = val;
    },

    // 跟踪状态下拉框change事件
    selectChange(val) {
      // 当跟踪状态选择未跟踪/继续跟踪/成功结束跟踪时，失败原因置灰不能填写，当跟踪状态为失败结束跟踪时，失败原因为必填项
      if (val === 80581004) {
        this.formList.find(x => x.fieldName === 'reviewFailed').rules = [{ required: true, message: '这是必填字段', trigger: 'blur' }];
        this.formList.find(x => x.fieldName === 'reviewFailed').disabled = false;
      } else {
        this.formList.find(x => x.fieldName === 'reviewFailed').rules = [];
        this.formList.find(x => x.fieldName === 'reviewFailed').initialValue = '';
        this.formList.find(x => x.fieldName === 'reviewFailed').disabled = true;
      }
      this.formList = [...this.formList];
    },

    changeHandle() {}
  }
};
</script>

<style lang="less" scoped>
.form-group {
  margin-top: 10px;
  span {
    height: 50px;
    line-height: 50px;
    text-align: right;
    width: 250px;
    padding-left: 100px;
  }
}
</style>
